package com.z.xhelper.core.config;

import com.z.xhelper.core.eventbus.EventBus;
import com.z.xhelper.core.socket.WebSocket;
import com.z.xhelper.core.utils.LogUtil;
import com.z.xhelper.core.wx.WxService;


import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class BeanContainer {

    /**
     * 当前服务的Bean容器
     */
    private static final HashMap<String, Object> beanContainer = new HashMap<>();

    /**
     * 添加 bean 到 bean 容器
     */
    public static <T> void addBean(Class<T> clz, Object bean) {
        if (beanContainer.containsKey(clz.getName())) {
            LogUtil.log("beanContainer already contains key: " + clz.getName());
            return;
        }
        if (bean == null) {
            LogUtil.log("bean is null");
            return;
        }
        beanContainer.put(clz.getName(), bean);
    }

    public static <T> void addBean(Class<T> clz, Object bean,boolean isReplace) {
        if (!isReplace && beanContainer.containsKey(clz.getName())) {
            LogUtil.log("beanContainer already contains key: " + clz.getName());
            return;
        }
        if (bean == null) {
            LogUtil.log("bean is null");
            return;
        }
        beanContainer.put(clz.getName(), bean);
    }

    /**
     * 从 bean 容器中获取 bean
     */
    public static <T> T getBean(Class<T> clz) {
        if (!beanContainer.containsKey(clz.getName())) {
            LogUtil.log("beanContainer not contains key: " + clz.getName());
            return null;
        }
        return (T) beanContainer.get(clz.getName());
    }


    public static void scanPackage(String packageName) {
        // xposed hook 当前模块 得到安卓上下文
        Reflections reflections = new Reflections(packageName);
        addBean(Reflections.class,reflections);
        // 注册 EventBus
        addBean(EventBus.class, new EventBus());
        // 注册 SocketClient
        addBean(WebSocket.class, new WebSocket());
        // 注册 wxService
        addBean(WxService.class, new WxService());
    }

    public static List<Class<?>> listBean(){
        return beanContainer.keySet().stream().map(key->{
            try {
                return Class.forName(key);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            return null;
        }).collect(Collectors.toList());
    }
}
